<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\product\Product;
use app\models\product\Product as Model;
use app\models\product\ProductAreaList;
use app\models\product\ProductSku;
use app\models\system\SetExpressCity;
use app\models\system\SetFlow;
use app\models\user\User;
use app\models\user\UserLevel;
use app\redis\Cache;
use app\util\Qrcode;
use app\util\Util;
use app\controllers\h5\services\Product as Service;

/**
 * Class ProductController
 * @package app\controllers\h5
 */
class ProductController extends H5Controller
{
    /**
     * like product
     *
     * @return \yii\web\Response
     */
    public function actionLike()
    {
        $key = Cache::$PRODUCT_LIKE;
        $cache = Cache::get($key);
        if (!$cache) {
            $num = SetFlow::getLastOne();
            $num = $num->recommend_num;

            $list = Model::find()
                ->where(['status' => Model::$statusMapping['OK']])
                ->orderBy(['is_recommend' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC])
                ->limit($num)
                ->with(['mainImage'])
                ->asArray()
                ->all();

            Cache::set($key, json_encode($list));
        } else {
            $list = json_decode($cache, true);
        }

        return $this->successEncode($list);
    }

    /**
     * all product list
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $key = Cache::$PRODUCT_LIST . $page;
        $cache = Cache::get($key);
        if (!$cache || true) {
            $query = Model::find()
                ->where(['status' => Model::$statusMapping['OK']]);

            $totalCount = $query->count();
            $totalPage = ceil($totalCount / $pageSize);

            $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->with(['mainImage', 'scoreCost', 'area', 'area.name'])
                ->asArray()
                ->all();

            Cache::set($key, json_encode([
                'totalCount' => $totalCount,
                'totalPage' => $totalPage,
                'list' => $list
            ]));
        } else {
            $data = json_decode($cache, true);
            $totalCount = $data['totalCount'];
            $totalPage = $data['totalPage'];
            $list = $data['list'];
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 新产品
    public function actionNewList()
    {
        $product_ids = ProductAreaList::find()
            ->where(['area_id' => [Product::$areaMap['NEW1'], Product::$areaMap['NEW2']]])
            ->select(['product_id'])
            ->column();


        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->where(['status' => Model::$statusMapping['OK']])
            ->andWhere(['id' => $product_ids]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['mainImage', 'scoreCost'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    /**
     * product detail
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionDetail()
    {
        $id = $this->post('id');

        $key = Cache::$PRODUCT_DETAIL . $id;
        $cache = Cache::get($key);
        if (!$cache || true) {
            $data = Model::find()
                ->where(['status' => Model::$statusMapping['OK']])
                ->andWhere(['id' => $id])
                ->with([
                    'mainImage',
                    'image', 'image.image',
                    'brand', 'brand.image',
                    'area', 'area.name',
                    'properties',
                    'scoreCost',
                    'sku', 'skuName', 'skuName.values', 'sku.image',
                    'scoreCost'
                ])
                ->asArray()
                ->one();
            if ($data) {

                // freight area
                $list = SetExpressCity::getName();
                $data['expressCity'] = $list;

                // area (select first & check group area)
                $area = $data['area'];
                if (is_array($area) && count($area) > 0) {
                    $data['isGroup'] = Service::checkGroupArea($area);
                    $data['area'] = $area[0];
                } else {
                    $data['area'] = null;
                    $data['group'] = false;
                }

                // content images list
                $convert = Util::convertImages($data['content']);
                $data['inImages'] = $convert['images'];
                $data['inText'] = $convert['text'];
                unset($data['content']);

                // sku
                if (is_array($data['sku'])) {
                    foreach ($data['sku'] as &$item) {
                        $item['sku_values'] = ProductSku::skuValue($item['sku_list']);
                    }
                }

                Cache::set($key, json_encode($data));
            }
        } else {
            $data = json_decode($cache, true);
        }

        if ($data) {
            return $this->successEncode($data);
        }

        return $this->fail('商品不存在');
    }

    // qrcode share
    public function actionQrcodeShare()
    {
        $id = $this->post('id');
        $url = $this->post('url');
        $color = $this->post('color');

        $name = '/qrcode/product-share/' . $id . '.png';
        $path = \Yii::$app->getBasePath() . '/web' . $name;

        // if (!file_exists($path)) {
        //     Qrcode::generate($url, $name, 100, $color);
        // }

        $u = User::findOne(['id' => $this->user->id]);
        if ($u->level >= UserLevel::$keys['vip1']) {
            $url .= '/' . $u->id;
        }

        // var_dump($url);exit;

        Qrcode::generate($url, $name, 100, $color);

        return $this->successEncode([
            'image' => $name
        ]);
    }
}